<template>
  <el-card class="box-card">
    <div slot="header">
      <span>添加账号</span>
    </div>
    <!-- 表单 -->
    <el-form
      label-width="80px"
      :model="ruleForm"
      class="form"
      :rules="rules"
      status-icon
      ref="ruleRef"
    >
      <!-- 账号 -->
      <el-form-item label="账号" prop="account">
        <el-input v-model="ruleForm.account"></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>
      <!-- 用户组 -->
      <el-form-item label="用户组" prop="userGroup">
        <el-select placeholder="请选择用户组" v-model="ruleForm.userGroup">
          <el-option label="超级管理员" value="超级管理员"></el-option>
          <el-option label="普通用户" value="普通用户"></el-option>
        </el-select>
      </el-form-item>
      <!-- 添加、重置 -->
      <el-form-item>
        <el-button type="primary" @click="submit">添加</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
//解构ajax函数
import {addUserReq, checkUserRepeatReq} from '@/api/user'

// 用户验证
const validateAccount = async (rule, value, callback) => {
  //非空验证
  if (!value) {
    callback(new Error('用户名不能为空'))
    //正则验证
  } else if (!/^[\u4E00-\u9FA5a-zA-Z0-9]{4,16}$/.test(value)) {
    callback(new Error('请输入4-12位由数字、字母、中文、下划线'))
    //账号重复验证
  } else {
    let res = await checkUserRepeatReq({
      account: value,
    })
    //解构数据
    let {code, msg} = res.data
    //判断
    if (code === 200) {
      callback()
    } else {
      callback(new Error(msg))
    }
  }
}
// 密码验证
const validatePassword = (rule, value, callback) => {
  //非空验证
  if (!value) {
    return callback(new Error('密码不能为空'))
    //正则验证
  } else if (!/^[a-zA-Z0-9_-]{4,16}$/.test(value)) {
    callback(new Error('数字,英文4-16位'))
  } else {
    callback()
  }
}
export default {
  data() {
    return {
      ruleForm: {
        account: '',
        password: '',
        userGroup: '',
      },
      rules: {
        account: [{validator: validateAccount, trigger: 'blur'}],
        password: [{validator: validatePassword, trigger: 'blur'}],
        userGroup: {required: true, message: '请选择用户组', trigger: 'blur'},
      },
    }
  },
  methods: {
    // 提交
    submit() {
      this.$refs.ruleRef.validate(async valid => {
        if (valid) {
          //发送请求
          let res = await addUserReq(this.ruleForm)
          //解构数据
          let {code, msg} = res.data
          //判断
          if (code === 0) {
            //跳转
            this.$router.push('/account')
          }
        }
      })
    },
    // 重置
    reset() {
      this.$refs.ruleRef.resetFields()
    },
  },
}
</script>

<style lang="scss" scoped>
.form {
  width: 300px;
}
</style>
